<template>
  <!-- 出院信息确认弹窗 -->
  <el-dialog
    v-model="visibleProxy"
    title="出院信息确认"
    width="520px"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
  >
    <div class="dialog-body">
      <!-- 出院信息表单 -->
      <el-form ref="formRef" :model="form" :rules="rules" label-width="96px" status-icon>
        <!-- 出院医嘱 -->
        <el-form-item label="出院医嘱" prop="orderType">
          <el-select v-model="form.orderType" placeholder="请选择">
            <el-option v-for="opt in orderTypeOptions" :key="opt" :label="opt" :value="opt" />
          </el-select>
        </el-form-item>

        <!-- 出院时间（默认当前时间） -->
        <el-form-item label="出院时间" prop="dischargeTime">
          <el-date-picker
            v-model="form.dischargeTime"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm"
            format="YYYY-MM-DD HH:mm"
            :default-time="defaultNow"
            placeholder="请选择"
          />
        </el-form-item>

        <!-- 停长嘱时间（精确到分钟） -->
        <el-form-item label="停长嘱时间" prop="stopAdviceTime">
          <el-date-picker
            v-model="form.stopAdviceTime"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm"
            format="YYYY-MM-DD HH:mm"
            :default-time="defaultNow"
            placeholder="请选择"
          />
        </el-form-item>

        <!-- 出院原因（多行） -->
        <el-form-item label="出院原因" prop="dischargeReason">
          <el-input v-model="form.dischargeReason" type="textarea" :rows="3" placeholder="请输入出院原因" />
        </el-form-item>

        <!-- 出院带药与药品选择 -->
        <el-form-item>
          <el-checkbox v-model="form.hasMedication">出院带药</el-checkbox>
        </el-form-item>

        <el-form-item v-if="form.hasMedication" label="药品类别" prop="drugCategories">
          <el-checkbox-group v-model="form.drugCategories">
            <el-checkbox v-for="c in drugCategoryOptions" :key="c" :label="c">{{ c }}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>

        <el-form-item v-if="form.hasMedication" label="药品选择" prop="selectedDrugs">
          <el-input
            v-model="selectedDrugsDisplay"
            readonly
            placeholder="选择药品"
            class="drug-input"
            @click="drugDialogVisible = true"
          >
            <template #append>
              <el-button @click="drugDialogVisible = true">选择药品</el-button>
            </template>
          </el-input>
        </el-form-item>
      </el-form>
    </div>

    <!-- 底部操作按钮 -->
    <template #footer>
      <span class="dialog-footer">
        <el-button type="primary" @click="onConfirm">确定</el-button>
        <el-button @click="onCancel">取消</el-button>
      </span>
    </template>

    <!-- 药品选择弹窗（预留逻辑） -->
    <el-dialog v-model="drugDialogVisible" title="选择药品" width="560px" append-to-body>
      <div class="drug-selector">
        <!-- 预留：此处应替换为药品检索与选择组件 -->
        <el-alert title="药品选择弹窗功能预留：当前为示例勾选" type="info" :closable="false" />
        <div class="drug-list">
          <el-checkbox-group v-model="tempSelectedDrugs">
            <el-checkbox v-for="d in demoDrugOptions" :key="d" :label="d">{{ d }}</el-checkbox>
          </el-checkbox-group>
        </div>
      </div>

      <template #footer>
        <el-button type="primary" @click="applyDrugSelection">确定</el-button>
        <el-button @click="drugDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </el-dialog>
</template>

<script setup name="DischargeDialog">
// 使用 Vue3 Composition API 编写逻辑，并添加必要中文注释
import { ref, reactive, computed, watch, onMounted } from 'vue'
import { dischargeConfirm } from '@/api/residentDoctor/clinicalRecords'

// 父子双向绑定：通过 v-model:visible 控制弹窗显示
const props = defineProps({
  visible: { type: Boolean, default: false },
  // 传入患者信息，用于合法性时间校验（例如不得早于入院时间）
  patient: { type: Object, default: () => ({}) }
})

const emit = defineEmits(['update:visible', 'submit'])

// 计算属性实现 v-model:visible 双向绑定
const visibleProxy = computed({
  get: () => props.visible,
  set: v => emit('update:visible', v)
})

// 表单模型：所有字段均为必填
const form = reactive({
  orderType: '常规出院',
  dischargeTime: '',
  stopAdviceTime: '',
  dischargeReason: '',
  hasMedication: false,
  drugCategories: [],
  selectedDrugs: []
})

// 出院医嘱选项
const orderTypeOptions = ['常规出院', '转院', '自动出院']

// 药品类别演示选项（可替换为字典）
const drugCategoryOptions = ['抗生素', '止痛药', '维生素', '止咳药']

// 药品选择弹窗相关状态
const drugDialogVisible = ref(false)
const demoDrugOptions = ['阿莫西林胶囊', '布洛芬片', '维生素C片', '氨溴索口服液']
const tempSelectedDrugs = ref([])

// 选中药品显示文案
const selectedDrugsDisplay = computed(() => (form.selectedDrugs.length ? form.selectedDrugs.join('、') : ''))

// 默认时间：当前时间（用于日期组件 default-time）
const defaultNow = new Date()

// 弹窗打开时，设置默认时间为当前时刻（精确到分钟）
watch(
  () => props.visible,
  v => {
    if (v) {
      const nowStr = formatDateMinute(new Date())
      form.dischargeTime = nowStr
      form.stopAdviceTime = nowStr
    }
  }
)

// 表单引用与校验规则
const formRef = ref(null)

// 通用必填校验
const requireRule = { required: true, message: '必填项不能为空', trigger: 'blur' }

// 合法性校验：时间不能早于入院时间、停长嘱时间不得晚于出院时间
const rules = {
  orderType: [requireRule],
  dischargeTime: [requireRule, { validator: validateDischargeTime, trigger: 'change' }],
  stopAdviceTime: [requireRule, { validator: validateStopLongOrderTime, trigger: 'change' }],
  dischargeReason: [requireRule],
  drugCategories: [{ validator: validateDrugCategories, trigger: 'change' }],
  selectedDrugs: [{ validator: validateSelectedDrugs, trigger: 'change' }]
}

// 时间格式化（到分钟）
function formatDateMinute(date) {
  const y = date.getFullYear()
  const m = String(date.getMonth() + 1).padStart(2, '0')
  const d = String(date.getDate()).padStart(2, '0')
  const hh = String(date.getHours()).padStart(2, '0')
  const mm = String(date.getMinutes()).padStart(2, '0')
  return `${y}-${m}-${d} ${hh}:${mm}`
}

// 字符串转日期（支持 YYYY-MM-DD HH:mm）
function toDate(val) {
  if (!val) return null
  const t = val.replace(/-/g, '/')
  return new Date(t)
}

// 校验：出院时间不得早于入院时间
function validateDischargeTime(rule, value, callback) {
  if (!value) return callback(new Error('必填项不能为空'))
  const discharge = toDate(value)
  if (!discharge || isNaN(discharge.getTime())) return callback(new Error('时间格式不合法'))

  // 如果传入了入院时间，校验不得早于入院
  const checkIn = props.patient?.checkInTime ? toDate(props.patient.checkInTime) : null
  if (checkIn && discharge.getTime() < checkIn.getTime()) {
    return callback(new Error('出院时间不得早于入院时间'))
  }
  callback()
}

// 校验：停长嘱时间必须早于或等于出院时间
function validateStopLongOrderTime(rule, value, callback) {
  if (!value) return callback(new Error('必填项不能为空'))
  const stopTime = toDate(value)
  const discharge = toDate(form.dischargeTime)
  if (!stopTime || isNaN(stopTime.getTime())) return callback(new Error('时间格式不合法'))
  if (discharge && stopTime.getTime() > discharge.getTime()) {
    return callback(new Error('停长嘱时间不得晚于出院时间'))
  }
  callback()
}

// 校验：当选择出院带药时，类别与具体药品均需要选择
function validateDrugCategories(rule, value, callback) {
  if (!form.hasMedication) return callback()
  if (!Array.isArray(value) || value.length === 0) return callback(new Error('请至少选择一种药品类别'))
  callback()
}

function validateSelectedDrugs(rule, value, callback) {
  if (!form.hasMedication) return callback()
  if (!Array.isArray(value) || value.length === 0) return callback(new Error('请选择具体药品'))
  callback()
}

// 药品选择应用
function applyDrugSelection() {
  form.selectedDrugs = [...tempSelectedDrugs.value]
  drugDialogVisible.value = false
}

// 提交：通过校验后，向父组件派发 submit 事件
function onConfirm() {
  formRef.value?.validate(valid => {
    if (!valid) return
    dischargeConfirm({
      ...form,
      patientId: props.patient.patientId,
      hospitalizationNumber: props.patient.hospitalizationNumber
    }).then(res => {
      if (res.code === 200) {
        ElMessage.success('出院确认成功')
        emit('submit', { ...form })
        visibleProxy.value = false
      }
    })
  })
}

// 取消：关闭弹窗
function onCancel() {
  visibleProxy.value = false
}

// 打开弹窗时重置临时药品选择
watch(
  () => drugDialogVisible.value,
  v => {
    if (v) tempSelectedDrugs.value = [...form.selectedDrugs]
  }
)

// 初始化：确保默认值为当前时间（首次挂载备用）
onMounted(() => {
  const nowStr = formatDateMinute(new Date())
  if (!form.dischargeTime) form.dischargeTime = nowStr
  if (!form.stopAdviceTime) form.stopAdviceTime = nowStr
})
</script>

<style scoped lang="scss">
@use '@/assets/styles/variables.module.scss' as *;

.dialog-body {
  padding: $padding-md;
}

.el-form {
  .el-select,
  .el-date-picker,
  .el-input {
    width: 100%;
  }
}

.drug-input {
  width: 100%;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: $margin-sm;
}

.drug-selector {
  padding: $padding-md;
  .drug-list {
    margin-top: $margin-md;
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    grid-gap: $margin-sm;
  }
}

/* 响应式：窄屏下栅格改为单列 */
@media (max-width: 600px) {
  .drug-selector .drug-list {
    grid-template-columns: 1fr;
  }
}
</style>
